import os;
import time
import utime
from machine import Pin
import network
import ntptime
from machine import RTC
from machine import PWM




#舵机控制主文件
pwm0 = PWM(Pin(14))      # create PWM object from a pin
pwm0.freq(50)         # set frequency 20ms
pwm0.duty(1)          # set duty cycle
p13 = Pin(2, Pin.OUT)    # led指示灯
p_motor = Pin(16, Pin.OUT)    # create output pin on GPIO0
p_motor.off()
def  wifi_init():
	# do_connect():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    time.sleep(3);
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('ChinaUnicom-1D69', 'bcg12345')
		# wlan.connect('Imilab-Office', 'Imilab$88888') # 连接到指定ESSID网络
        while not wlan.isconnected():
            time.sleep(1);
        print('network config:', wlan.ifconfig());

def  led_blink_show_status(timeout):
	i = 0;
	while i < timeout:
		# print("hello world "+str(i));
		time.sleep_ms(250);
		if i % 2 == 0:
			p13.on()  # set pin to "on" (high) level
		else:
			p13.off() # set pin to "off" (low) level
		i = i + 1
	p13.on()
def  ntp_sync_rtc():
	print("sync rtc form ntp")
	ntptime.host = 'time.windows.com'
	ntptime.settime()
	tm = ntptime.time()  # 获取网络时间（从 1970 年 1 月 1 日开始的秒数）
	tm = tm+ 8*3600 #东8区
	year, month, day, hour, minute, second, _, _ = utime.localtime(tm)  # 转换为元组形式
	print("Network Time:", year, month, day, hour, minute, second)# 输出结果
	rtc = RTC()  # 初始化 RTC
	rtc.datetime((year, month, day, 0, hour, minute, second, 0))  # 同步 RTC 时间

	# year, month, day, weekday, hour, minute, second, subsecond = rtc.datetime()
	# rtc_time = utime.mktime((year+30, month, day, hour, minute, second, 0, 0))#年份使用2000+
	# rtc_time -= 8*3600
	# print("rtc=", year, month, day, weekday, hour, minute, second, subsecond)
	# print("1970 seconds=", rtc_time)

def  duoji_pwm_ctrl(duty_set):
	# pwm0 = PWM(Pin(0))      # create PWM object from a pin
	# pwm0.freq()             # get current frequency
	# pwm0.freq(1000)         # set frequency
	# pwm0.duty()             # get current duty cycle
	# pwm0.duty(duty_set)          # set duty cycle
	# pwm0.deinit()           # turn off PWM on the pin
	pwm2 = PWM(Pin(2), freq=500, duty=512) # create and configure in one go
	time.sleep(3);
	pwm2.deinit();
def Servo(servo, angle):
    # angle / 180（ * 2（0°-180°） + 0.5（）/ 20ms * 1023
    servo.duty(int(((angle)/180 *2 + 0.5) / 20 * 1023))  
def  test_duoji():


	count = 0
	Servo(pwm0,30)
	while  100:
		count = count + 1
		if  count == 1:
			Servo(pwm0,90)
			time.sleep(0.2)
		elif count == 2:
			Servo(pwm0,30)
			time.sleep(2)
			count = 0
		elif count == 3:
			Servo(pwm0,90)
		elif count == 4:
			Servo(pwm0,120)
		elif count == 5:
			Servo(pwm0,180)
			count = 0;
		print("pwd duty 0 -180 count={}".format(count))
	pwm0.deinit()           # turn off PWM on the pin

#此文件cp到设备上以后重命名为main.py,micropython 就可以开机运行
#文件先闪烁30次led,并开始初始化wifi连接,等wifi连接成功后再闪烁10次,然后启动后续
if __name__ == '__main__':
	test_duoji()
	led_blink_show_status(5)
	test_duoji()
	# wifi_init()
	# ntp_sync_rtc()
	# led_blink_show_status(5)

	

